<template>
  <div>
    <div class="flex-com mar-btm">
      <span v-if="iftttLogic" class="label-title font-weight-bold iconfont icon-branch"></span>
      <span v-else class="label-title">目标对象</span>
      <el-select v-model="ruleForm.type" size="mini" placeholder="触发对象" class="width-input" @change="resetVar">
        <el-option v-for="(item, index) in tigerOption" :key="index" :label="item.name" :value="item.key"></el-option>
      </el-select>
    </div>
    <!--房间属性-->
    <div v-if="ruleForm.type === 'relatedSystem'">
      <div class="flex-com mar-btm">
        <span v-if="iftttLogic" class="label-title font-weight-bold iconfont icon-branch"></span>
        <span v-else class="label-title">房间属性</span>
        <el-select v-model="ruleForm.room" size="mini" placeholder="房间属性" class="width-input" @change="finalKey">
          <el-option
            v-for="(item, index) in systemOption" :key="index"
            :label="item.name" :value="item.key"></el-option>
        </el-select>
      </div>
    </div>
    <!--设备状态-->
    <div v-if="ruleForm.type === 'relatedDeviceStatus'">
      <div class="flex-com mar-btm">
        <span v-if="iftttLogic" class="label-title font-weight-bold iconfont icon-branch"></span>
        <span v-else class="label-title">目标设备</span>
        <el-select
          v-model="ruleForm.controlId" size="mini"
          placeholder="设备名称" class="width-input"
          @change="resetDevice">
          <el-option
            v-for="(item, index) in deviceList" :key="index"
            :label="`${item.deviceOtherName?item.deviceOtherName:item.deviceName}`" :value="item._id"></el-option>
        </el-select>
      </div>
      <div class="flex-com mar-btm" v-if="ruleForm.controlId">
        <span v-if="iftttLogic" class="label-title font-weight-bold iconfont icon-branch"></span>
        <span v-else class="label-title">设备命令</span>
        <el-select
          v-model="ruleForm.command" size="mini"
          placeholder="设备命令" class="width-input"
          @change="changeCommand">
          <el-option
            v-for="(item, index) in findDeviceCommands(ruleForm.controlId)" :key="index"
            :label="item.commandName" :value="item.methodName"></el-option>
        </el-select>
      </div>
      <div v-if="ruleForm.command">
        <div class="flex-com mar-btm" v-if="paramsList.uniqueKey">
          <!--只有有uniqueKey,params有枚举就枚举 没有手输入-->
          <span v-if="iftttLogic" class="label-title font-weight-bold iconfont icon-branch"></span>
          <span v-else class="label-title">{{paramsList.uniqueKey}}</span>
          <el-select
            v-if="uniqueKeyList(paramsList).length > 0"
            v-model="ruleForm.uniqueKey"
            :placeholder="`输入${paramsList.uniqueKey}`"
            size="mini" class="width-input"
            @change="finalKey">
            <el-option
              v-for="(item, index) in uniqueKeyList(paramsList)" :key="index"
              :label="item.paramAlias" :value="item.paramKey"></el-option>
          </el-select>
          <el-input
            v-else v-model="ruleForm.uniqueKey"
            :placeholder="`输入${paramsList.uniqueKey}`"
            size="mini" class="width-input"
            @input="forceUpdate($event)"
            @blur="finalKey"></el-input>
        </div>
        <!--有npk 输入索引-->
        <div class="flex-com mar-btm" v-if="showNpIndex">
          <span v-if="iftttLogic" class="label-title font-weight-bold iconfont icon-branch"></span>
          <span v-else class="label-title">索引</span>
          <el-input-number
            v-model="ruleForm.npKeyIndex"
            :min="0" :max="100"
            placeholder="输入索引"
            controls-position="right"
            size="mini" class="width-input"
            @change="finalKey"></el-input-number>
        </div>
        <!--选参数-->
        <div class="flex-com mar-btm">
          <span v-if="iftttLogic" class="label-title font-weight-bold iconfont icon-branch"></span>
          <span v-else class="label-title">设备参数</span>
          <el-select
            v-model="ruleForm.params" size="mini"
            placeholder="设备参数" class="width-input"
            @change="judgeParams">
            <el-option
              v-for="(item, index) in deviceParams(paramsList)" :key="index"
              :label="item.paramAlias"
              :value="item.paramKey"></el-option>
          </el-select>
        </div>

      </div>
    </div>
    <!--组件变量-->
    <div v-if="ruleForm.type === 'relatedAtomic'">
      <div class="flex-com mar-btm">
        <span v-if="iftttLogic" class="label-title font-weight-bold iconfont icon-branch"></span>
        <span v-else class="label-title">触发组件</span>
        <el-input
          :value="getAtomicAttr(ruleForm.atomic, 'name')"
          disabled size="mini"
          placeholder="选择组件"
          class="width-input"></el-input>
        <span class="font-color-primary font-weight-bold cursor-pointer" @click="showPicker()">选择</span>
      </div>
      <div class="flex-com mar-btm" v-if="ruleForm.atomic">
        <span v-if="iftttLogic" class="label-title font-weight-bold iconfont icon-branch"></span>
        <span v-else class="label-title">组件变量</span>
        <el-select
          v-model="ruleForm.atomicPorts" size="mini"
          placeholder="选择修改项" class="width-input"
          @change="(value)=>changePorts(value,ruleForm)">
          <el-option
            v-for="(state, index) in getAtomicAttr(ruleForm.atomic, 'ports')" :key="index"
            :label="state.name" :value="state.key"></el-option>
        </el-select>
      </div>
    </div>
    <!--全局变量-->
    <div v-if="ruleForm.type === 'relatedGlobal'">
      <div class="flex-com mar-btm">
        <span v-if="iftttLogic" class="label-title font-weight-bold iconfont icon-branch"></span>
        <span v-else class="label-title">全局变量</span>
        <el-select v-model="ruleForm.globalVar" size="mini" class="width-input"
                   @change="(value) => changeGlobal(value, ruleForm)">
          <el-option
            v-for="(global, index) in globalVarList" :key="index"
            :label="global.name" :value="global.key"></el-option>
        </el-select>
      </div>
    </div>
  </div>
</template>
<script>
  import {getAtomicAttr, findDeviceCommands, findCommandParams, generateUID} from "@/utils";
  import {mapActions, mapState} from "vuex";

  export default {
    name: 'IftttFiled',
    props: {
      ruleForm: {
        type: Object,
        default: () => {
          return {};
        },
      },
      iftttLogic: {
        type: Boolean,
        default: () => {
          return false;
        },
      },
    },
    data() {
      return {
	      tigerOption: [
		      {name: "房间属性", key: "relatedSystem"},
		      {name: "设备状态", key: "relatedDeviceStatus"},
		      {name: "组件变量", key: "relatedAtomic"},
		      {name: "全局变量", key: "relatedGlobal"},
	      ],
        systemOption: [
          {name: "当前情景", key: "curGroupCmd"},
          {name: "自动共享", key: "autoSharing"},
          {name: "是否有人占用", key: "occupied"},
          {name: "是否开启系统", key: "systemOn"},
        ],
        currentWidgetId: "",
        curPickerId: '',
        getAtomicAttr: getAtomicAttr,
        findDeviceCommands: findDeviceCommands,
        findCommandParams: findCommandParams,
        paramsList: {}
      };
    },
    computed: {
      ...mapState({
	      globalDeviceList: (state) => state.ide.globalDeviceList,
	      globalVarList: (state) => state.ide.globalVarList,
        widgetPickerInfo: state => state.ide.widgetPickerInfo,
      }),
      deviceList() {
        //组合自定义命令和设备命令到一个组
        return this.globalDeviceList.map(device => device);
      },
      showNpIndex() {
        //console.log(12377, this.paramsList, this.ruleForm)
        //有npStoreKey就展示索引 没有就判断storeKey在不在npKeyFields
        if (this.paramsList.npKeyFields && this.paramsList.npKey) {
          if (this.ruleForm.storeKey && this.paramsList.npKeyFields.includes(this.ruleForm.params)) {
            return true
          } else if (!this.paramsList.npStoreKey && !this.ruleForm.storeKey && this.paramsList.npKeyFields.includes(this.ruleForm.params)) {
            return true
          } else {
            return false
          }
        }
      },
    },
    watch: {
      'widgetPickerInfo.selectWidgetId': {
        handler(selectWidgetId) {
          if (!selectWidgetId) return;
          const {pickerId = ''} = this.widgetPickerInfo;
          if (this.curPickerId !== pickerId) return;
	        if (this.currentWidgetId === selectWidgetId) return;
          this.ruleForm.atomic = selectWidgetId;
          this.$emit('resetOperator');
          this.ruleForm.atomicPorts = '';
          this.$forceUpdate();
        }
      },
      'ruleForm.command':{
        //命令变了重新加载参数列表
        handler(command) {
          this.getParamsList(command);
        }
      }
    },
    mounted() {
      this.getParamsList(this.ruleForm.command);
    },
    methods: {
      ...mapActions(['updateWidgetPickerInfo']),
      //回显paramsList
      getParamsList(val) {
        const commandList = this.findDeviceCommands(this.ruleForm.controlId) || [];
        this.paramsList = {...commandList.find(item => item.methodName === val) || {}};
      },
      showPicker() {
        this.currentWidgetId = this.ruleForm.atomic;
        this.curPickerId = generateUID();
        this.updateWidgetPickerInfo({
          show: true,
          pickerId: this.curPickerId,
          selectWidgetId: this.currentWidgetId
        });
      },
      //清空数据
      resetDevice() {
        this.ruleForm.command = "";
        this.ruleForm.params = "";
        this.ruleForm.uniqueKey = '';
        this.ruleForm.destStoreKey = '';
        this.ruleForm.npKey = "";
        this.ruleForm.npStoreKey = "";
        this.ruleForm.npKeyIndex = 0;
        this.ruleForm.storeKey = "";
        // this.finalKey();
        this.forceUpdate();
      },
      resetCommand() {
        this.ruleForm.params = "";
      },
      //选择设备命令事件
      changeCommand(val) {
        this.getParamsList(val)
        this.ruleForm.params = "";
        this.ruleForm.value = "";
        this.ruleForm.uniqueKey = '';
        this.ruleForm.npKeyIndex = 0;
        this.ruleForm.npStoreKey = this.paramsList.npStoreKey || '';
        this.ruleForm.npKey = this.paramsList.npKey || '';
        this.ruleForm.destStoreKey = this.paramsList.destStoreKey || '';
        this.ruleForm.storeKey = "";
        // this.finalKey();
        this.forceUpdate();
      },
      //有uniqueKey,params有枚举就枚举 没有手输入
      uniqueKeyList(paramsList) {
        const list = paramsList.params.find((item) => {
          return item.paramKey === paramsList.uniqueKey;
        });
        return list ? list : [];
      },
      deviceParams(paramsList = {}) {
        const {params = []} = paramsList;
        return params.filter(item => item.paramKey !== paramsList.uniqueKey);
      },
      forceUpdate() {
        this.$forceUpdate();
      },
      changePorts(val, item) {
        const ports = getAtomicAttr(item.atomic, 'ports');
        item.portsType = ports.find(item => item.key === val).type;
        this.finalKey();
      },
      //更改全局变量
      changeGlobal(value, item) {
        item.portsType = this.globalVarList.find(item => item.key === value).type;
        this.finalKey();
      },
      //判断选择参数内有没有storeKey
      judgeParams(val) {
        this.getParamsList(this.ruleForm.command);//重新请求命令，更改监听引用
        let paramsList = this.deviceParams(this.paramsList)
        const current = paramsList.find(item => item.paramKey === val);
        this.ruleForm.storeKey = current.storeKey ? current.storeKey : '';
        this.finalKey();
      },
      finalKey() {
        switch (this.ruleForm.type) {
          case 'relatedSystem':
            const room = this.systemOption.find(item => item.key === this.ruleForm.room);
            this.ruleForm.value = `room.${this.ruleForm.room}`;
            this.ruleForm.name = `房间属性：${room.name}`;
            break;
          case 'relatedDeviceStatus':
            const device = this.deviceList.find((item) => {
              return item._id === this.ruleForm.controlId;
            });
            this.ruleForm.name = `设备属性：${device.deviceOtherName?device.deviceOtherName:device.deviceName}-“${this.ruleForm.params}”`;
            //判断选择参数有没有storeKey 数组>1就是有 this.ruleForm.params=storeKey.paramKey
            const npStoreKey = this.ruleForm.npStoreKey ? `${this.ruleForm.npStoreKey}.` : ''
            const storeKey = this.ruleForm.storeKey ? `${this.ruleForm.storeKey}.` : ''
            /*
            *分两种情况，没有destStoreKey 和有destStoreKey
            ***1.没有destStoreKey****
              * 1.1有npk ,有storeKey ，判断paramKey是否在npKeyFields里，如果判断存在，就用npStoreKey；不存在就是storeKey.paramKey
              * 1.2无npk ,storeKey.paramKey
            ***2.有destStoreKey****
              * 2.1只有uniqueKey ,没有npk，比较srcStoreKey===storeKey，判断正确 destStoreKey.uniqueKey.paramKey,不正确就是storeKey.paramKey
              * 2.2有uniqueKey ,有npk，判断paramKey是否在npKeyFields里，存在就是：destStoreKey.uniqueKey.npKey.index.paramKey，不存在就是storeKey.paramKey
            * **/
            if (!this.ruleForm.destStoreKey) {
              if (this.ruleForm.npKey) {
                if (this.ruleForm.storeKey && this.paramsList.npKeyFields.includes(this.ruleForm.params)) {
                  // console.log('paramKey 在 npk数组 ，storeKey存在')
                  this.ruleForm.value = `${this.ruleForm.controlId}.${npStoreKey}${this.ruleForm.npKey}.${this.ruleForm.npKeyIndex}.${this.ruleForm.params}`;
                } else if (!this.ruleForm.storeKey && this.paramsList.npKeyFields.includes(this.ruleForm.params)) {
                  // console.log('paramKey 在 npk数组 ，storeKey不存在')
                  this.ruleForm.value = `${this.ruleForm.controlId}.${npStoreKey}${this.ruleForm.npKey}.${this.ruleForm.npKeyIndex}.${this.ruleForm.params}`;
                } else {
                  //console.log('paramKey 不在 npk数组')
                  this.ruleForm.value = `${this.ruleForm.controlId}.${storeKey}${this.ruleForm.params}`;
                }
              } else {
                /*有storeKey/无storeKey 通过ruleForm.params已经判断*/
                this.ruleForm.value = `${this.ruleForm.controlId}.${storeKey}${this.ruleForm.params}`;
              }
            } else {
              if (this.paramsList.uniqueKey && !this.ruleForm.npKey) {
                if (this.ruleForm.storeKey && this.paramsList.srcStoreKey === this.ruleForm.storeKey) {
                  //console.log('有storeKey 通过srcStoreKey===storeKey')
                  /*只有uniqueKey srcStoreKey与storeKey一样*/
                  this.ruleForm.value = `${this.ruleForm.controlId}.${this.ruleForm.destStoreKey}.${this.ruleForm.uniqueKey}.${this.ruleForm.params}`;
                } else if (this.ruleForm.storeKey && this.paramsList.srcStoreKey !== this.ruleForm.storeKey) {
                  // console.log('有storeKey 通过srcStoreKey!==storeKey',)
                  this.ruleForm.value = `${this.ruleForm.controlId}.${storeKey}${this.ruleForm.params}`;
                } else if (!this.ruleForm.storeKey) {
                  // console.log('没有storeKey，')
                  this.ruleForm.value = `${this.ruleForm.controlId}.${this.ruleForm.destStoreKey}.${this.ruleForm.uniqueKey}.${this.ruleForm.params}`;
                }
              } else if (this.paramsList.uniqueKey && this.ruleForm.npKey) {
                if (this.ruleForm.storeKey && this.paramsList.npKeyFields.includes(this.ruleForm.params)) {
                  this.ruleForm.value = `${this.ruleForm.controlId}.${this.ruleForm.destStoreKey}.${this.ruleForm.uniqueKey}.${this.ruleForm.npKey}.${this.ruleForm.npKeyIndex}.${this.ruleForm.params}`;
                } else if (!this.ruleForm.storeKey && this.paramsList.npKeyFields.includes(this.ruleForm.params)) {
                  this.ruleForm.value = `${this.ruleForm.controlId}.${this.ruleForm.destStoreKey}.${this.ruleForm.uniqueKey}.${this.ruleForm.npKey}.${this.ruleForm.npKeyIndex}.${this.ruleForm.params}`;
                } else {
                  this.ruleForm.value = `${this.ruleForm.controlId}.${storeKey}${this.ruleForm.params}`;
                }
              }
            }
            break;
          case 'relatedAtomic':
            this.ruleForm.value = `${this.ruleForm.atomic}.${this.ruleForm.atomicPorts}`;
            const widgetValues = getAtomicAttr(this.ruleForm.atomic, 'ports');
            const widgetValuesName = widgetValues.find(v => v.key === this.ruleForm.atomicPorts).name;
            this.ruleForm.name = `组件属性：${this.getAtomicAttr(this.ruleForm.atomic, 'name')}的${widgetValuesName}`;
            break;
          case 'relatedGlobal':
            const globalVar = this.globalVarList.find(item => item.key === this.ruleForm.globalVar);
            this.ruleForm.value = this.ruleForm.globalVar;
            this.ruleForm.name = `全局变量：${globalVar.name}`;
            break;
          default:
            break;
        }
        this.forceUpdate();
        this.$emit('resetOperator');
      },
      resetVar() {
        this.ruleForm.params = '';
        this.ruleForm.command = '';
        this.ruleForm.controlId = '';
        this.ruleForm.atomic = '';
        this.ruleForm.room = '';
        this.ruleForm.globalVar = '';
        this.ruleForm.value = '';
        this.ruleForm.name = '';
        this.ruleForm.portsType = '';
        this.ruleForm.storeKey = '';
        this.$emit('resetOperator');
      }
    }
  }
</script>
<style lang="less" scoped>
  .flex-com-cont {
    display: flex;
    align-items: center;
    width: 100%;
    flex-wrap: wrap;
  }

  .flex-com {
    display: flex;
    align-items: center;
    gap: 10px;

  }

  .label-title {
    min-width: 60px;
    color: @colorGray10;
    font-size: 14px;
    text-align: center;
    flex-shrink: 0;
  }

  .width-input {
    width: 350px;

    /deep/ .el-input__inner {
      width: 100%;
    }
  }
</style>
